package com.slipper.system.codeless.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.constants.Constants;
import com.slipper.core.cache.CacheKey;
import com.slipper.core.cache.CacheUtil;
import com.slipper.core.message.MessageUtil;
import com.slipper.core.message.Topic;
import com.slipper.util.Tool;
import com.slipper.system.codeless.bo.DataModelBO;
import com.slipper.util.UUID;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.codeless.dao.DataTableDao;
import com.slipper.system.codeless.bo.DataTableBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;

@Service
@ReadTransactional
public class DataTableService {
    @Resource
    private DataTableDao dataTableDao;
    @Resource
    private DataTableFieldService dataTableFieldService;
    @Resource
    private DataTableOrdinalService dataTableOrdinalService;
    @Resource
    private PrivilegeService privilegeService;
    
    public DataTableBO queryBy(String id) {
        if (Tool.isBlank(id)) {
            return null;
        }

        DataTableBO dataTable = CacheUtil.get(CacheKey.DataTable.PREFIX + id, DataTableBO.class);
        if (dataTable == null) {
            dataTable = dataTableDao.queryBy(id);
            if (dataTable == null) return null;

            dataTable.setPrivilegeList(privilegeService.queryBySourceId(id));
            dataTable.setOrdinalList(dataTableOrdinalService.queryByTableId(id));
            dataTable.setFieldList(dataTableFieldService.queryByTableId(id));
            CacheUtil.set(CacheKey.DataTable.PREFIX + id, dataTable, 60 * 60);
        }

        return dataTable;
    }
    
    public List<DataTableBO> queryList(DataTableBO bo) {
        return dataTableDao.queryList(bo);
    }
    
    public PageInfo<DataTableBO> queryPage(DataTableBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(dataTableDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(DataTableBO bo) {
        if (Tool.isBlank(bo.getDefaultTable())) {
            bo.setDefaultTable(Constants.NO);
        }

        int result = 0;
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            result += dataTableDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            result += dataTableDao.insert(bo);
        }

        result += privilegeService.save(bo.getId(), bo.getPrivilegeList(), bo.getCurrEmpId());
        result += dataTableFieldService.save(bo.getId(), bo.getFieldList(), bo.getCreateId());
        result += dataTableOrdinalService.save(bo.getId(), bo.getOrdinalList(), bo.getCreateId());

        CacheUtil.remove(CacheKey.DataTable.PREFIX + bo.getId());
        MessageUtil.publish(Topic.DATA_TABLE_CHANGE);

        return result;
    }

    @WriteTransactional
    public void saveList(List<DataTableBO> list) {
        if (list == null) return;

        list.forEach(item -> {
            if (dataTableDao.queryBy(item.getId()) != null) {
                item.setUpdateTime(System.currentTimeMillis());
                dataTableDao.update(item);
            } else {
                item.setUpdateTime(System.currentTimeMillis());
                item.setCreateTime(System.currentTimeMillis());
                dataTableDao.insert(item);
            }
            CacheUtil.remove(CacheKey.DataTable.PREFIX + item.getId());
        });
    }

    @WriteTransactional
    public void deleteByModelId(String modelId) {
        if (Tool.isBlank(modelId)) {
            return;
        }

        DataTableBO qo = new DataTableBO();
        qo.setModelId(modelId);
        dataTableDao.queryList(qo).forEach(this::delete);
    }
    
    @WriteTransactional
    public int delete(DataTableBO bo) {
        if (Tool.isBlank(bo.getId())) {
            return 0;
        }

        dataTableFieldService.deleteByTableId(bo.getId());
        dataTableOrdinalService.deleteByTableId(bo.getId());
        privilegeService.deleteBySourceId(bo.getId());
        int result = dataTableDao.delete(bo.getId());
        CacheUtil.remove(CacheKey.DataTable.PREFIX + bo.getId());
        return result;
    }

    @WriteTransactional
    public void createDefault(DataModelBO bo) {
        if (dataTableDao.queryByDefault(bo.getId()) > 0) {
            return;
        }

        DataTableBO table = new DataTableBO();
        table.setId(UUID.getUUID());
        table.setModelId(bo.getId());
        table.setName(bo.getName() + "(默认表格)");
        table.setShowHeader(Constants.YES);
        table.setShowFull(Constants.YES);
        table.setShowCheckbox(Constants.YES);
        table.setShowOrdinal(Constants.YES);
        table.setShowOperate(Constants.YES);
        table.setShowPagination(Constants.YES);
        table.setShowBorder(Constants.YES);
        table.setTotalJson(Constants.NO);
        table.setUpdateId(bo.getUpdateId());
        table.setCreateId(bo.getCreateId());
        table.setDefaultPageSize(20);
        table.setDefaultTable(Constants.YES);
        table.setUpdateTime(System.currentTimeMillis());
        table.setCreateTime(System.currentTimeMillis());
        dataTableDao.insert(table);

        dataTableFieldService.createDefault(table.getId(), bo);
    }

    @WriteTransactional
    public int copy(DataTableBO bo) {
        if (Tool.isBlank(bo.getId())) {
            return 0;
        }

        // 复制 DataTableBO
        DataTableBO newTable = dataTableDao.queryBy(bo.getId());
        if (newTable == null) {
            return 0;
        }

        newTable.setId(UUID.getUUID());
        newTable.setName(newTable.getName() + "_复制");
        newTable.setDefaultTable(Constants.NO);
        newTable.setUpdateId(bo.getUpdateId());
        newTable.setCreateId(bo.getCreateId());
        newTable.setUpdateTime(System.currentTimeMillis());
        newTable.setCreateTime(System.currentTimeMillis());
        dataTableDao.insert(newTable);

        privilegeService.copyBySourceId(bo.getId(), newTable.getId(), bo.getCreateId());
        dataTableFieldService.copyByTableId(bo.getId(), newTable.getId(), bo.getCreateId());
        dataTableOrdinalService.copyByTableId(bo.getId(), newTable.getId(), bo.getCreateId());
        return 1;
    }
}
